let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0;
let allStudents = [];
let filteredStudents = [];
let currentEditingStudentId = null;
let classOptions = [];

function validateStudentSno(sno) {
    const errors = [];

    if (!sno || sno.trim() === '') {
        errors.push('学号不能为空');
    } else if (sno.trim().length > 50) {
        errors.push('学号长度不能超过50个字符');
    }

    return errors;
}

function validateStudentName(name) {
    const errors = [];

    if (!name || name.trim() === '') {
        errors.push('姓名不能为空');
    } else if (name.trim().length > 50) {
        errors.push('姓名长度不能超过50个字符');
    }

    return errors;
}

function validateStudentClass(classId) {
    const errors = [];

    if (!classId || classId === '') {
        errors.push('请选择班级');
    }

    return errors;
}

function validateStudentPassword(password) {
    const errors = [];

    if (!password || password.trim() === '') {
        errors.push('密码不能为空');
    } else if (password.trim().length > 50) {
        errors.push('密码长度不能超过50个字符');
    }

    return errors;
}

function checkStudentExists(sno, excludeId = null) {
    const trimmedSno = sno.trim();

    return allStudents.some(student =>
        student.sno === trimmedSno &&
        student.id !== excludeId
    );
}

document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

function initializePage() {
    loadClassOptions();
    loadStudents();
    bindEvents();
}

function bindEvents() {
    document.getElementById('searchInput').addEventListener('input', debounce(filterStudents, 300));
    document.getElementById('classFilter').addEventListener('change', filterStudents);
    document.getElementById('addStudentForm').addEventListener('submit', handleAddStudent);
    document.getElementById('editStudentForm').addEventListener('submit', handleEditStudent);
    document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteStudent);
    document.getElementById('addStudentModal').addEventListener('hidden.bs.modal', resetAddForm);
    document.getElementById('editStudentModal').addEventListener('hidden.bs.modal', resetEditForm);
}

async function loadClassOptions() {
    try {
        const response = await fetch('/api/classes/options');
        const result = await response.json();

        if (result.success) {
            classOptions = result.data;
            populateClassSelects();
            populateClassFilter();
        } else {
            console.error('加载班级选项失败:', result.msg, result.error);
            showError('加载班级选项失败：' + result.msg);
        }
    } catch (error) {
        console.error('加载班级选项出错:', error);
        showError('加载班级选项失败：网络错误');
    }
}

function populateClassSelects() {
    const addSelect = document.getElementById('addStudentClass');
    const editSelect = document.getElementById('editStudentClass');
    
    addSelect.innerHTML = '<option value="">请选择班级</option>';
    editSelect.innerHTML = '<option value="">请选择班级</option>';
    
    // 添加班级选项
    classOptions.forEach(classItem => {
        const option = document.createElement('option');
        option.value = classItem.id;
        option.textContent = classItem.display;
        
        addSelect.appendChild(option.cloneNode(true));
        editSelect.appendChild(option);
    });
}

function populateClassFilter() {
    const filterSelect = document.getElementById('classFilter');
    
    // 清空现有选项（保留默认选项）
    filterSelect.innerHTML = '<option value="">所有班级</option>';
    
    // 添加班级选项
    classOptions.forEach(classItem => {
        const option = document.createElement('option');
        option.value = classItem.id;
        option.textContent = classItem.display;
        filterSelect.appendChild(option);
    });
}

async function loadStudents() {
    showLoading();

    try {
        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });

        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }

        const classFilter = document.getElementById('classFilter').value;
        if (classFilter) {
            params.append('class_id', classFilter);
        }

        const response = await fetch(`/api/students?${params}`);
        const result = await response.json();

        if (result.success) {
            const data = result.data;
            allStudents = data.items;
            filteredStudents = [...allStudents];

            totalPages = data.pagination.total_pages;
            currentPage = data.pagination.current_page;
            totalCount = data.pagination.total_count;

            displayStudents();
        } else {
            console.error('加载学生数据失败:', result.msg, result.error);
            showError('加载失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
            showEmptyState();
        }
    } catch (error) {
        console.error('加载学生数据出错:', error);
        showError('加载失败：网络错误');
        displayStudents();
    }
}

function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('studentTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'none';
}

function showEmptyState() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('studentTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    updateStudentCount(0);
}

function displayStudents() {
    document.getElementById('loadingSpinner').style.display = 'none';

    if (filteredStudents.length === 0) {
        showEmptyState();
        return;
    }

    document.getElementById('studentTableContainer').style.display = 'block';
    document.getElementById('emptyState').style.display = 'none';

    renderStudentTable(filteredStudents);
    renderPagination();
    updateStudentCount(totalCount);
}

function renderStudentTable(students) {
    const tbody = document.getElementById('studentTableBody');
    tbody.innerHTML = '';
    
    students.forEach(student => {
        const row = document.createElement('tr');
        row.className = 'fade-in';
        row.innerHTML = `
            <td><strong>${student.sno}</strong></td>
            <td>${student.name}</td>
            <td><span class="badge bg-info">${student.class_display}</span></td>
            <td><span class="text-muted">••••••••</span></td>
            <td>${formatDateTime(student.created_time)}</td>
            <td>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm"
                            onclick="editStudent(${student.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm"
                            onclick="deleteStudent(${student.id}, '${student.sno} - ${student.name}')" title="删除">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function renderPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
            上一页
        </a>
    `;
    pagination.appendChild(prevLi);
    
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
            pagination.appendChild(li);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(li);
        }
    }
    
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
            下一页
        </a>
    `;
    pagination.appendChild(nextLi);
}

function updateStudentCount(count) {
    document.getElementById('listCount').textContent = count;
}

function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) return;
    currentPage = page;
    loadStudents();
}

function filterStudents() {
    currentPage = 1;
    loadStudents();
}

function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('classFilter').value = '';
    currentPage = 1;
    loadStudents();
}

async function handleAddStudent(event) {
    event.preventDefault();

    const form = event.target;
    const formData = new FormData(form);

    const studentData = {
        sno: formData.get('sno').trim(),
        name: formData.get('name').trim(),
        class_id: parseInt(formData.get('class_id')),
        password: formData.get('password').trim()
    };

    // 验证数据
    const errors = [];
    errors.push(...validateStudentSno(studentData.sno));
    errors.push(...validateStudentName(studentData.name));
    errors.push(...validateStudentClass(studentData.class_id));
    errors.push(...validateStudentPassword(studentData.password));

    if (checkStudentExists(studentData.sno)) {
        errors.push(`学号 ${studentData.sno} 已存在`);
    }

    if (errors.length > 0) {
        showError('数据验证失败：\n' + errors.join('\n'));
        return;
    }

    try {
        const response = await fetch('/api/students', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(studentData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess('学生添加成功！');
            bootstrap.Modal.getInstance(document.getElementById('addStudentModal')).hide();
            loadStudents();
        } else {
            showError('添加失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('添加学生出错:', error);
        showError('添加失败：网络错误');
    }
}

function editStudent(studentId) {
    const student = allStudents.find(s => s.id === studentId);
    if (!student) {
        showError('找不到要编辑的学生');
        return;
    }

    currentEditingStudentId = studentId;

    document.getElementById('editStudentId').value = student.id;
    document.getElementById('editStudentSno').value = student.sno;
    document.getElementById('editStudentName').value = student.name;
    document.getElementById('editStudentClass').value = student.class_id;
    document.getElementById('editStudentPassword').value = student.password;

    const modal = new bootstrap.Modal(document.getElementById('editStudentModal'));
    modal.show();
}

async function handleEditStudent(event) {
    event.preventDefault();

    const form = event.target;
    const formData = new FormData(form);

    const studentData = {
        sno: formData.get('sno').trim(),
        name: formData.get('name').trim(),
        class_id: parseInt(formData.get('class_id')),
        password: formData.get('password').trim()
    };

    // 验证数据
    const errors = [];
    errors.push(...validateStudentSno(studentData.sno));
    errors.push(...validateStudentName(studentData.name));
    errors.push(...validateStudentClass(studentData.class_id));
    errors.push(...validateStudentPassword(studentData.password));

    if (checkStudentExists(studentData.sno, currentEditingStudentId)) {
        errors.push(`学号 ${studentData.sno} 已存在`);
    }

    if (errors.length > 0) {
        showError('数据验证失败：\n' + errors.join('\n'));
        return;
    }

    try {
        const response = await fetch(`/api/students/${currentEditingStudentId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(studentData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess('学生更新成功！');
            bootstrap.Modal.getInstance(document.getElementById('editStudentModal')).hide();
            loadStudents();
        } else {
            showError('更新失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('更新学生出错:', error);
        showError('更新失败：网络错误');
    }
}

function deleteStudent(studentId, studentInfo) {
    currentEditingStudentId = studentId;
    document.getElementById('deleteStudentInfo').textContent = studentInfo;

    const modal = new bootstrap.Modal(document.getElementById('deleteStudentModal'));
    modal.show();
}

async function handleDeleteStudent() {
    try {
        const response = await fetch(`/api/students/${currentEditingStudentId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('deleteStudentModal')).hide();
            loadStudents();
        } else {
            showError('删除失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('删除学生出错:', error);
        showError('删除失败：网络错误');
    }
}

function resetAddForm() {
    const form = document.getElementById('addStudentForm');
    form.reset();
    form.classList.remove('was-validated');

    // 清除所有验证状态
    const inputs = form.querySelectorAll('.form-control, .form-select');
    inputs.forEach(input => {
        input.classList.remove('is-invalid', 'is-valid');
    });
}

function resetEditForm() {
    const form = document.getElementById('editStudentForm');
    form.reset();
    form.classList.remove('was-validated');
    currentEditingStudentId = null;

    // 清除所有验证状态
    const inputs = form.querySelectorAll('.form-control, .form-select');
    inputs.forEach(input => {
        input.classList.remove('is-invalid', 'is-valid');
    });
}
